<?php

namespace App\Http\Controllers\Admin;

use App\Models\Material;

class MaterialController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(){

        if ($this->isOnSubmit()) {
            $items = $this->request->input('items');
            foreach (Material::whereIn('id', $items)->get() as $m){
                @unlink(storage_public_path($m->thumb));
                @unlink(storage_public_path($m->source));
                $m->delete();
            }
            return ajaxReturn();
        } else {

            $this->assign([
                'type'=>'image',
                'uid'=>'',
                'username'=>'',
                'name'=>'',
                'time_begin'=>'',
                'time_end'=>'',
                'material_types'=>trans('common.material_types')
            ]);
            $this->data['material_types'] = trans('common.material_types');

            $queryParams = [];
            $type = $this->request->get('type');
            $type = $type ? $type : 'image';
            $queryParams['type'] = $type;
            $query = Material::whereType($type);

            $uid = $this->request->input('uid');
            if ($uid) {
                $queryParams['uid'] = $uid;
                $query = $query->where('uid', $uid);
            }

            $username = $this->request->input('username');
            if ($username) {
                $queryParams['username'] = $username;
                $query = $query->where('username', $username);
            }

            $name = $this->request->input('name');
            if ($name) {
                $queryParams['name'] = $name;
                $query = $query->where('name', 'LIKE', "%$name%");
            }

            $time_begin = $this->request->input('time_begin');
            if ($time_begin) {
                $queryParams['time_begin'] = $time_begin;
                $query = $query->where('created_at', '>', strtotime($time_begin));
            }

            $time_end = $this->request->input('time_end');
            if ($time_end) {
                $queryParams['time_end'] = $time_end;
                $query = $query->where('created_at', '<', strtotime($time_end));
            }
            $this->assign($queryParams);

            $items = $query->orderByDesc('id')->paginate(20);
            $this->assign([
                'items'=>$items,
                'pagination'=>$items->appends($queryParams)->render()
            ]);

            return $this->view('admin.common.material');
        }
    }
}
